package com.demo.common.utils.encrypt;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
import org.springframework.util.Assert;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/** 推荐用这个
 * @author pengj
 * @description
 * @date 2017-12-12 21:51
 */
public class Base64Util {


    /**
     * 把字节数组按UTF_8编码为字符串
     *
     * @param bytes
     * @return
     * @throws Exception
     */
    public static String encryptBASE64AsString(byte[] bytes) throws Exception {
        return new Base64().encodeAsString(bytes);
    }

    public static byte[] encryptBASE64AsBytes(String key) throws Exception {
        return new Base64().encode(StringUtils.getBytesUtf8(key));
    }

    /**
     * 把字符编码为 base64
     * @param key
     * @return
     * @throws Exception
     */
    public static String encryptBASE64(String key) throws Exception {
        Assert.notNull(key,"被加密数据为null");
        return new Base64().encodeAsString(StringUtils.getBytesUtf8(key));
    }

    /**
     * 按 base64 编码
     *
     * @param bytes
     * @return
     * @throws Exception
     */
    public static byte[] encryptBASE64(byte[] bytes) throws Exception {
        return new Base64().encode(bytes);
    }


    /**
     * 解码 base64 数据
     * @param key
     * @return
     * @throws Exception
     */
    public static String decryptBASE64AsString(byte[] key) throws Exception {
        return newString(new Base64().decode(key), StandardCharsets.UTF_8);
    }

    public static byte[] decryptBASE64AsBytes(String key) throws Exception {
        return new Base64().decode(key);
    }

    /**
     * 解码 base64 base utf-8
     *
     * @param key
     * @return
     * @throws Exception
     */
    public static String decryptBASE64(String key) throws Exception {
        Assert.notNull(key,"被解密数据为null");
        return newString(new Base64().decode(key), StandardCharsets.UTF_8);
    }

    /**
     * 解码base64
     *
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decryptBASE64(byte[] key) throws Exception {
        return new Base64().decode(key);
    }




    private static String newString(final byte[] bytes, final Charset charset) {
        return bytes == null ? null : new String(bytes, charset);
    }

    public static void main(String[] args) throws Exception {
        String name = "http://www.baidu.com/sim=中国";
        byte[] encrypt = Base64Util.encryptBASE64AsBytes(name);
        System.out.println("加密 = " + encrypt);
        String dename = Base64Util.decryptBASE64AsString(encrypt);
        System.out.println("解密 = "+dename);
    }

}
